<?php
	date_default_timezone_set('America/Argentina/Buenos_Aires');

 	include_once('./dbcon.php');

 	define("APP_ID", "519942634775590");
	define("SECRET", "5ea51129a4ca16efdaa478bbddeb1465");
	define("APP_CANVAS", "http://www.pageposter.solo-dilo.com/");

	// Facebook PHP SDK v4.0.11

	// include required files form Facebook SDK

	require_once( '../Facebook/HttpClients/FacebookHttpable.php' );
	require_once( '../Facebook/HttpClients/FacebookCurl.php' );
	require_once( '../Facebook/HttpClients/FacebookCurlHttpClient.php' );

	require_once( '../Facebook/Entities/AccessToken.php' );
	require_once( '../Facebook/Entities/SignedRequest.php' );

	require_once( '../Facebook/FacebookSession.php' );
	require_once( '../Facebook/FacebookRedirectLoginHelper.php' );
	require_once( '../Facebook/FacebookRequest.php' );
	require_once( '../Facebook/FacebookResponse.php' );
	require_once( '../Facebook/FacebookSDKException.php' );
	require_once( '../Facebook/FacebookRequestException.php' );
	require_once( '../Facebook/FacebookOtherException.php' );
	require_once( '../Facebook/FacebookAuthorizationException.php' );
	require_once( '../Facebook/GraphObject.php' );
	require_once( '../Facebook/GraphSessionInfo.php' );
	require_once( '../Facebook/FacebookPermissionException.php' );

	use Facebook\HttpClients\FacebookHttpable;
	use Facebook\HttpClients\FacebookCurl;
	use Facebook\HttpClients\FacebookCurlHttpClient;

	use Facebook\Entities\AccessToken;
	use Facebook\Entities\SignedRequest;

	use Facebook\FacebookSession;
	use Facebook\FacebookRedirectLoginHelper;
	use Facebook\FacebookRequest;
	use Facebook\FacebookResponse;
	use Facebook\FacebookSDKException;
	use Facebook\FacebookRequestException;
	use Facebook\FacebookOtherException;
	use Facebook\FacebookAuthorizationException;
	use Facebook\GraphObject;
	use Facebook\GraphSessionInfo;
	use Facebook\FacebookPermissionException;


	error_reporting(E_ALL);

	$user_token = null;

	// IE compatible
	header('P3P: CP="NOI ADM DEV PSAi NAV OUR STP IND DEM"');

	// start session
	session_start();

	// init app with app id and secret
	FacebookSession::setDefaultApplication( APP_ID, SECRET );

	// login helper with redirect_uri
	$helper = new FacebookRedirectLoginHelper( APP_CANVAS );

	// see if a existing session exists
	if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
		// create new session from saved access_token
		$session = new FacebookSession( $_SESSION['fb_token'] );

		// validate the access_token to make sure it's still valid
		try {
			if ( !$session->validate() ) {
				$session = null;
			}
		} catch ( Exception $e ) {
			// catch any exceptions
			$session = null;
		}
	}  

	// Try to create session by saved token
	if ( !isset( $session ) ) {
		$session = new FacebookSession( $user_token );

		// validate the access_token to make sure it's still valid
		try {
			if ( !$session->validate() ) {
				$session = null;
			}
		} catch ( Exception $e ) {
			// catch any exceptions
			$session = null;
		}
	}

	if ( !isset( $session ) || $session === null ) {
		// no session exists

		try {
			$session = $helper->getSessionFromRedirect();
		} catch( FacebookRequestException $ex ) {
			// When Facebook returns an error
			// handle this better in production code
			print_r( $ex );
		} catch( Exception $ex ) {
			// When validation fails or other local issues
			// handle this better in production code
			print_r( $ex );
		}

	}

	// see if we have a session
	if ( isset( $session ) ) {

		// save the session
		$_SESSION['fb_token'] = $session->getToken();
		// create a session using saved token or the new one we generated at login
		$session = new FacebookSession( $session->getToken() );

		// graph api request for user data
		$request = new FacebookRequest( $session, 'GET', '/me' );
		$response = $request->execute();
		// get response
		$user_profile = $response->getGraphObject()->asArray();
		
		$access_token = $_SESSION['fb_token'];
		$user_token = $access_token;

		updateTokens($session);

	} else {
		echo '<script>top.location.href="'.$helper->getLoginUrl( array( 'manage_pages', 'publish_actions', 'publish_stream' ) ).'";</script>';
	}

	function updateTokens($session) {
		global $mysqli;
		global $user_token;

		$response = (new FacebookRequest(
				$session, 'GET', '/me/accounts?fields=username,access_token&limit=1000', array(
			'access_token' => $session->getToken()
			)
		))->execute()->getGraphObject();

		$pages = $response->getProperty('data')->asArray();
		$pages_query_condition = "WHERE ";

		for ($i = 0; $i < count($pages); $i++) {
			$page_id = ( isset($pages[$i]->username) ) ? $pages[$i]->username : $pages[$i]->id;
			$pages_query_condition = $pages_query_condition."fb_id = '".$page_id."'";
			if ($i < count($pages) - 1) $pages_query_condition = $pages_query_condition." OR ";
		}

		$pages_query = $mysqli->query("select fb_id from access_tokens ".$pages_query_condition);

		while ($row = $pages_query->fetch_assoc()) {
			for ($i = 0; $i < count($pages); $i++) {
				$page_id = ( isset($pages[$i]->username) ) ? $pages[$i]->username : $pages[$i]->id;

				if ($row['fb_id'] == $page_id) {
					 $mysqli->query("UPDATE access_tokens SET value = '".$pages[$i]->access_token."' WHERE fb_id = '".$row['fb_id']."'");
					 break;
				}
			}
		}

	}
?>

<html>
<head>
	<meta charset="UTF-8">
</head>
<body>
<?php
 	$posts = $mysqli->query("SELECT p.post_id, p.page_id, p.creation_date, p.likes, p.last_date_crawled, u.title FROM posts p, urls u WHERE p.url_id = u.id AND DATEDIFF(now(), creation_date) < 14 ORDER BY creation_date DESC");

	echo '<table border="1">';
	echo '<tr>';
	echo '<td>Titulo</td>';
	echo '<td>Publicacion</td>';
	echo '<td>Grupo</td>';
	echo '<td>Creation_date</td>';
	echo '<td>Likes</td>';
	echo '<td>Last_crawled_date</td>';
	echo '</tr>';

 	while ($row = $posts->fetch_assoc()) { 
 		echo '<tr>';
 		echo '<td>'.$row['title'].'</td>';
		echo '<td><a target="_blank" href="http://www.facebook.com/'.$row['post_id'].'">Entrar</td>';
		echo '<td><a target="_blank" href="http://www.facebook.com/'.$row['page_id'].'">'.$row['page_id'].'</td>';
		echo '<td>'.$row['creation_date'].'</td>';
		echo '<td>'.$row['likes'].'</td>';
		echo '<td>'.$row['last_date_crawled'].'</td>';
		echo '</tr>';
	}

	echo '</table>';
?>
</body>